// pages/orderInsert/index.js
import {
  ApiOrder,
  ApiGetOrderTimeList,
  ApiGetmyCoupon
} from '../../api/index'
import {
  debounce
} from "../../utils/index"
const app = getApp()
let {
  baseUrl,
  commonUpdate,
  commonUpload
} = app.globalData
Page({
  /**
   * 页面的初始数据
   */
  data: {
    autosize: {
      maxHeight: 500,
      minHeight: 100
    },
    isLoading: false,
    items: [{
      // 导航名称
      text: '2024-08-26',
      // 导航名称右上角徽标，1.5.0 版本开始支持
      badge: 3,
      // 禁用选项
      disabled: false,
      // 该导航下所有的可选项
      children: [{
          // 名称
          text: '温州',
          // id，作为匹配选中状态的标识
          id: 1,
          // 禁用选项
          disabled: true,
        },
        {
          text: '杭州',
          id: 2,
        },
      ],
    }, ],
    minHour: 10,
    maxHour: 20,
    minDate: new Date().getTime(),
    maxDate: new Date(2029, 10, 1).getTime(),
    currentDate: new Date().getTime(),
    opt: {
      order_time: "",
      patient_id: '',
      contact_id: '',
      order_model: '1',
      /*    need_material: 1, */
      patient_pic: '',
      patient_status: '',
    },
    showPopup: false,
    dataList: {},
    info: {},
    infoContact: {},
    fileList: [],
    //定义不展示数据
    fileListCopy: [],
    //服务时间
    activeId: null,
    mainActiveIndex: 0,
    navItem: '',
    actions: [{
        name: '拍照',
      },
      {
        name: '从相册中选取照片',
      },
      {
        name: '从微信中选取文件',
      },
    ],
    show: false,
    valData: [],
    isToday: true,
  },



  imageClick() {
    this.setData({
      show: true
    })
  },
  onSelect(event) {
    if (event.detail.name == '拍照') {
      let query = {
        count: 1,
        mediaType: ['image'],
        sourceType: ['camera'],
        camera: 'back',
        /*  sourceType: ['album'],
         sizeType: ['original'], */
      }
      this.photoCommon(query, '照片')
    } else if (event.detail.name == '从相册中选取照片') {
      let query = {
        count: 1,
        mediaType: ['image'],
        /*      sourceType: ['camera'],
             camera: 'back', */
        sourceType: ['album'],
        sizeType: ['original'],
      }
      this.photoCommon(query, '从相册中选取照片')
    } else {
      this.afterRead()
    }
  },
  photoCommon(query, val) {
    let that = this
    let json = JSON
    wx.chooseMedia({
      ...query,
      success(res) {
        that.setData({
          type: res.type
        })
        wx.showLoading({
          title: `正在上传${val}`,
          mask: true
        })
        wx.uploadFile({
          url: baseUrl + commonUpdate,
          filePath: res.tempFiles[0].tempFilePath,
          header: {
            Authorization: 'Bearer ' + wx.getStorageSync('token')
          },
          name: 'file',
          success(res) {
            res.name = json.parse(res.data).data.path.match(/\.(\w+)$/)
            // 展示文件数据
            that.data.fileList.push({
              url: baseUrl + commonUpload + json.parse(res.data).data.path,
              name: res.name[1]
            })
            console.log(that.data.fileList)
            //传输后端
            that.data.fileListCopy.push(
              json.parse(res.data).data.path
            )
            that.setData({
              'opt.patient_pic': that.data.fileListCopy.toString(),
              fileList: that.data.fileList,
              show: false,
            })
            wx.showToast({
              title: '上传文件成功',
            })
          },
          fail(err) {
            console.log(err)
          }
        })
      },
      // fail(res) {
      //   console.log(res)
      //   console.log('图片拍摄失败')
      // }
    })
  },
  optFormateData(e) {
    this.setData({
      showPopup: true
    })
  },
  onClose() {
    this.setData({
      showPopup: false,
      show: false
    })
  },

  //患者信息
  getPatient() {
    let that = this
    wx.showModal({
      title: "请选择就诊人本人信息，否则无法提供上门服务！",
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/searchPatient/index?data=a&phone=${that.data.infoContact.phone}`,
          })
        }
      }
    })

  },
  //紧急联系人
  getContact() {
    console.log(this.data.info)

    wx.navigateTo({
      url: `/pages/searchContact/index?data=b&phone=${this.data.info.phone}`,
    })
  },
  //是否需要自备耗材
  /*   onChangeCheckbox(e) {
      let val = ''
      e.detail == true ? val = 1 : val = 0
      this.setData({
        'opt.need_material': val
      })
    }, */
  //就医证明文件上传
  afterRead() {
    let that = this
    console.log('222')
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      extension: ['.xlsx', '.xls', '.doc', '.docx', '.jpg', '.png', '.pdf', '.jpeg'],
      success: function (res) {
        // 文件选择成功
        var filePath = res.tempFiles[0].path;

        // 调用上传方法
        that.uploadFile(filePath);
      },
      fail: function (res) {
        // 文件选择失败
        console.log(res);
      }
    })
  },
  uploadFile(file, name) {
    console.log(file)
    let that = this
    let json = JSON
    wx.uploadFile({
      url: baseUrl + commonUpdate,
      filePath: file,
      name: 'file',
      header: {
        Authorization: 'Bearer ' + wx.getStorageSync('token')
      },
      success(res) {
        console.log('success', res)
        res.name = json.parse(res.data).data.path.match(/\.(\w+)$/)
        // 展示文件数据
        that.data.fileList.push({
          url: baseUrl + commonUpload + json.parse(res.data).data.path,
          name: res.name[1]
        })
        that.data.fileListCopy.push(
          json.parse(res.data).data.path
        )
        that.setData({
          'opt.patient_pic': that.data.fileListCopy.toString(),
          fileList: that.data.fileList
        })
        wx.showToast({
          title: '上传文件成功',
        })
      }
    })
  },

  //删除图片数据
  handleDelete(event) {
    console.log()
    let val = event.currentTarget.dataset.v.url
    const index = this.data.fileList.findIndex(item => {
      return item.url == val
    })
    console.log(index)
    /* if (index.length >= 0) { */
    this.data.fileList.splice(index, 1)
    this.data.fileListCopy.splice(index, 1)
    /*    } */
    this.setData({
      fileList: this.data.fileList,
      'opt.patient_pic': this.data.fileListCopy.toString(),
    })
  },

  onInput(e) {
    let currentDate = new Date(e.detail)
    this.setData({
      'opt.order_time': this.formatDate(currentDate).toString(),
      showPopup: false
    })
    /* let val = this.formatDate(currentDate);
 
     */
  },

  //转换时间
  getHalfHourIntervals(val) {
    let arr = val.split('-')
    let startTime = arr[0]
    let endTime = arr[1]
    const result = [];

    // Helper function to format minutes into HH:MM
    const formatTime = (minutes) => {
      const hours = String(Math.floor(minutes / 60)).padStart(2, '0');
      const mins = String(minutes % 60).padStart(2, '0');
      return `${hours}:${mins}`;
    };

    // Helper function to parse HH:MM into minutes
    const parseTime = (time) => {
      const [hours, mins] = time.split(':').map(Number);
      return hours * 60 + mins;
    };

    let startMinutes = parseTime(startTime);
    const endMinutes = parseTime(endTime);

    // Start from the nearest half-hour interval greater than or equal to startTime
    let adjustStartMinutes = Math.ceil(startMinutes / 30) * 30;

    while (adjustStartMinutes <= endMinutes) {
      result.push({
        text: formatTime(adjustStartMinutes)
      });
      adjustStartMinutes += 30; // Move to next half-hour interval
    }

    return result;
  },



  formatDate(date) {
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, '0');
    let day = String(date.getDate()).padStart(2, '0');
    let hours = String(date.getHours()).padStart(2, '0');
    let minutes = String(date.getMinutes()).padStart(2, '0');
    let seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getOrderTime(true)
    this.setData({
      dataList: JSON.parse(options.dataList)
    })
  },
  //获取时间
  getOrderTime(isToday) {
    let val = []
    ApiGetOrderTimeList().then(res => {
      res.data.forEach((item, index) => {
        val.push({
          text: item.time
        })
      });
      if (isToday) {
        this.setData({
          valData: this.judgeTime(val)
        })
      } else {
        this.setData({
          valData: val
        })
      }
      //拿到近七天的日期
      this.getDatesOneWeekFromNow()
    })
  },


  //判断当前时间是否在这个时间的前面
  judgeTime(arr) {
    const timeSlots = arr;
    const currentTime = new Date();
    // 获取当前时间的小时和分钟，取前四个小时才行
    const currentHours = currentTime.getHours() + 4;
    const currentMinutes = currentTime.getMinutes();
    // 遍历 timeSlots 并移除时间已过的项
    const updatedTimeSlots = timeSlots.filter(({
      text
    }) => {
      const endTimeText = text.slice(0, 12).split('-')[1]; // 结束时间
      const [endHours, endMinutes] = endTimeText.split(':').map(Number); // 解析小时和分钟
      // 判断当前时间是否在结束时间之前
      console.log(currentHours, endHours)
      return !(currentHours > endHours || (currentHours === endHours && currentMinutes >= endMinutes));
    });
    return updatedTimeSlots
  },
  //得到日期
  getDatesOneWeekFromNow() {
    let now = new Date();
    let dates = [];
    for (let i = 0; i < 7; i++) {
      let date = new Date(now);
      date.setDate(now.getDate() + i);
      dates.push({
        text: this.formatDateVal(date),
        children: this.data.valData
      });
    }
    this.setData({
      items: dates
    })

    /*    return dates; */
  },
  formatDateVal(date) {
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, '0');
    let day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  //得到时间
  /*  getTimesInHalfHourIntervals(startHour, endHour) {
     console.log(startHour, endHour)
     let times = [];
     let current = new Date();
     current.setHours(startHour, 0, 0, 0);
     while (current.getHours() < endHour) {
       times.push({
         text: this.formatTime(current)
       });
       current.setMinutes(current.getMinutes() + 30); // Move to the next half-hour interval
     }
     return times;
   }, */
  formatTime(date) {
    let hours = String(date.getHours()).padStart(2, '0');
    let minutes = String(date.getMinutes()).padStart(2, '0');

    return `${hours}:${minutes}`;
  },

  //切换单选狂
  onChangeRadio(e) {
    this.setData({
      'opt.order_model': e.detail
    })
  },
  //患者状态
  contentInput(e) {
    const type = e.currentTarget.dataset.v
    this.setData({
      [`opt.${type}`]: e.detail
    })
  },

  //
  onClickItem({
    detail = {}
  }) {
    this.data.navItem = this.data.navItem.length > 0 ? this.data.navItem : this.data.items[0].text
    if (this.data.navItem.length > 0) {
      this.setData({
        'opt.order_time': this.data.navItem + ' ' + detail.text.slice(0, 12),
        showPopup: false
      })
    }

  },
  onClickNav({
    detail = {}
  }) {
    //判断是不是当天
    let isToday = this.isToday(this.data.items[detail.index].text)
    if (isToday) {
      this.getOrderTime(true)
    } else {
      this.getOrderTime(false)
    }
    /*  判断当前时间比今天打 */
    this.setData({
      navItem: this.data.items[detail.index].text,
      isToday: isToday
    })
  },
  //判断是不是当天



  isToday(date) {
    //Code goes here.
    var d = new Date(date.toString().replace(/-/g, "/"));
    var todaysDate = new Date();
    if (d.setHours(0, 0, 0, 0) == todaysDate.setHours(0, 0, 0, 0)) {
      return true;
    } else {
      return false;
    }
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1]; //当前页面
    let info = currPage.data?.info
    let infoContact = currPage.data?.infoContact

    if (info) {
      this.setData({
        'opt.patient_id': info.id,
        info
      })
    }

    if (infoContact) {
      this.setData({
        'opt.contact_id': infoContact.id,
        infoContact
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  handleOrder() {
    let that = this
    let pic_required = this.isRequired(this.data.dataList.patient_pic_required, this.data.opt.patient_pic, '就医证明')
    let status_required = this.isRequired(this.data.dataList.patient_status_required, this.data.opt.patient_status, '病情描述及备注')
    if (pic_required && status_required) {
      if (this.data.dataList.allow_refund == 0) {
        wx.showModal({
          title: "注意：该订单不允许退款！",
          success(res) {
            if (res.confirm) {
              that.getAddOrder()
            }
          }
        })
      } else {
        that.getAddOrder()
      }
    }
  }, //下单
  getAddOrder: debounce(function () {
    let that = this
    console.log(this.data.dataList)
    this.setData({
      isLoading: true,
    })
    ApiOrder({
      item_id: this.data.dataList.id,
      coupon_id: that.data.dataList?.coupon_id || "",
      extend_price: this.data.dataList.extend_price,
      ...this.data.opt
    }).then(res => {
      if (res.code == '200') {
        wx.requestPayment({
          ...res.data,
          success(res) {
            /*        app.clearStatistics() */
            wx.showModal({
              title: '支付成功',
              showCancel: false,
              success(res) {
                that.setData({
                  isLoading: false
                })
                wx.reLaunch({
                  url: `/pages/orderList/index?data=${'全部'}`,
                })
              }
            })

          },
          fail(res) {
            that.setData({
              isLoading: false
            })
            wx.reLaunch({
              url: `/pages/orderList/index?data=${'全部'}`,
            })
          }


        })

      }
    }).finally(_ => {
      this.setData({
        isLoading: false,
      })
    })
  }, 1000, true),

  isRequired(val, data, label) {
    console.log(val, data)
    /*  dataList = {
       "allow_refund": 1,
       "id": 1,
       "patient_pic_required": 1,
       "patient_status_required": 1
     } */
    if (val == '1' && !data.length) {
      console.log(val, data, label)
      wx.showToast({
        title: '请输入' + label,
        icon: 'error'
      })
      return false
    } else {
      return true
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})